import { defineStore } from "pinia";
import {
  getGoodsPromptAPI,
  getChatHistoryAPI,
  getGoodsCategoryAPI,
  getChatListAPI,
  createChat,
  getCategoryCountAPI,
  deleteGoodsChatInfoAPI,
  changeGoodsChatInfo,
  sendCozeGoodPromptAPI,
  getMeetRecodsAPI,
  getCustomerRequireMentAPI,
  saveAiContentAPI
} from "@/services/productAssistant";
import { showToast, showLoadingToast, closeToast } from "vant";
import { http, cancelFetchRequest } from "@/utils/http";

// 步骤枚举
const StepType = {
  chooseCategory: 'chooseCategory',
  freeQA: 'freeQA',
  readStream: 'readStream',
  useMeetRecord: 'useMeetRecord',
}

// 消息方向枚举
const messageDirectionType = {
  send: 'send',
  received: 'received',
}

// 消息类型
const MessageTypes = {
  prompt: 'PROMPT',
  firstPromptQuestion: 'FIRST_PROMPT_QUESTION',
  seekPrompt: 'SEEK_PROMPT',
  recommend: 'RECOMMEND',
  topic: 'TOPIC',
  quote: 'QUOTE',
  answer: 'answer',
  followUp: 'follow_up',
  verbose: 'verbose'
}

// Coze消息事件类型
const CozeEventTypes = {
  Done: 'done',
  Message: 'message',

}

export const useProductStore = defineStore("productStore", {
  state: () => ({
    currentCategoryId: '',
    currentChatId: '',
    recordList: [],
    chatList: [],
    chatHistoryMap: {},
    categorys: [],
    promptQuestions: [],
    seekPromptQuestions: [],
    currentPromptIndex: 0,
    currentRecordItem: null,
    recommend: '',
    showExtra: false,
    showEditDialog: false,
    editChatId: '',
    dialogFieldValue: '',
    isBatchEdit: false,
    onCheckedRecord: [],
    currentStepType: StepType.chooseCategory,
    isLoading: false,
    isSafeWareProduct: false, // 是否为软件产品
    userId: '',
    suggestions: [],
    tempAnswer: '',
    meetRecords: [],
    selectedRecord: null,
    checkedRecord: null,
    meetRequireMent: '',
    isLoadingSuggestions: false, 
  }),
  actions: {

    newMsg() {
      this.chatList = []
      this.currentStepType = StepType.chooseCategory
      this.suggestions = []
      this.cancelRequest()
      this.addWelcomeMessage()
    },

    onSelectRecordItem(item) {
      this.currentRecordItem = item
      this.cancelRequest()
      this.getChatHistoryAction(item)
    },

    async changeGoodsChatName(name) {
      if (name.length === 0) {
        return
      }
      const res = await changeGoodsChatInfo({
        topic: name,
        chatId: this.editChatId
      })
      for (let index = 0; index < this.recordList.length; index++) {
        const element = this.recordList[index];
        if (element.id === this.editChatId) {
          element.topic = name
        }
      }
    },

    async pinnedGoodsChatInfo(chatId, pinned) {
      const res = await changeGoodsChatInfo({
        pinned,
        chatId: chatId
      })

      let pinnedNum = 0;
      let targetIndex = -1
      this.recordList.forEach((item, index) => {
        if (item.pinned) {
          pinnedNum++
        }
        if (item.id === chatId) {
          item.pinned = pinned
          targetIndex = index
        }
      })
      if (targetIndex >= 0) {
        pinnedNum = pinned ? pinnedNum : pinnedNum - 1
        this.recordList.splice(pinnedNum, 0, ...this.recordList.splice(targetIndex, 1));
      }
    },

    async deleteGoodsChatInfoAction(ids) {
      const res = deleteGoodsChatInfoAPI(ids)
      this.recordList = this.recordList.filter((item) => {
        return ids.indexOf(item.id) === -1
      })
    },

    async getGoodsCategoryAction() {
      const categorys = await getGoodsCategoryAPI()
      this.categorys = categorys
      return categorys
    },

    async getChatHistoryAction(item) {
      const { categoryId, id } = item
      const chatId = id
      const chatRecord = await getChatHistoryAPI(chatId)
      this.chatHistoryMap[chatId] = chatRecord
      this.chatList = []
      this.receivedMessage('Hello，我是你的智能商品推荐伙伴，请选择你要售卖的商品类型。', 'answer')
      for (const item of chatRecord) {
        const { messageType, ai, message } = item
        if (MessageTypes.topic === messageType) continue
        console.log('chat history item: ', item);
        let content = message
        if (ai) {
          if (message.startsWith("data:")) {
            // 兼容流式数据 （老版本：后期可以删除）
            this.handleHistoryMessageWithStream(content)
          } else {
            if (!this.isValidJSON(content)) {
              this.receivedMessage(content, 'answer')
              continue
            }
            const messageInfo = JSON.parse(content)
            const { questions, message } = messageInfo
            this.receivedMessage(message, 'answer')
            this.suggestions = questions.map((v) => {
              return v.content ? v : {content: v}
            })
          }
        } else {
          this.sendMessage(content)
        }
      }

      this.currentChatId = chatId
      this.currentCategoryId = categoryId
      this.setStep(StepType.freeQA)
    },

    isValidJSON(text) {
      try {
        JSON.parse(text);
        return true;
      } catch (error) {
        return false;
      }
    },


    // 处理历史消息未Stream形式
    handleHistoryMessageWithStream(message) {

      this.suggestions = []
      let lines = message.split("\n");
      let msgContent = ''
      for (let i = 0; i < lines.length - 1; i++) {
        let line = lines[i].trim();
        if (!line.startsWith("data:")) continue;
        line = line.slice(5).trim();
        let chunkObj;
        try {
          if (line.startsWith("{")) {
            chunkObj = JSON.parse(line);
          } else {
            continue;
          }
        } catch (error) {
          console.error("Error parsing chunk:", error);
          continue;
        }
        const { event } = chunkObj
        if (event === CozeEventTypes.Message) {
          const { message } = chunkObj
          const { type, content, role, content_type } = message
          if (
            role === "assistant" &&
            type === "answer"
          ) {
            if (content.length === 0) continue
            msgContent += content
          }

          if (role === "assistant" &&
            type === "follow_up") {
            this.suggestions.push(message)
          }
        }
        if (event === CozeEventTypes.Done) {
          this.receivedMessage(msgContent, 'answer')
        }
      }
    },

    async getGoodsPromptAction(item) {
      let { id, name, questions } = item
      questions = JSON.parse(questions)
      const count = await getCategoryCountAPI(id)
      if (count <= 0) {
        showToast('未上架')
        return
      }
      console.log('questions: ', questions);
      const res = await createChat({ topic: name, categoryId: id })
      console.log('getGoodsPromptAction :>> ', res);
      this.isSafeWareProduct = (name.indexOf('软件产品') != -1)
      this.currentCategoryId = id
      this.currentChatId = res.id
      this.sendCozeGoodPromptAction(name)
    },

    async getChatListAction(page, pageSize = 20) {
      const data = await getChatListAPI({
        pageSize: pageSize,
        pageNumber: page,
        topicType: 'PRODUCT_RECOMMENDATION',
        searchKey: ''
      })
      if (page === 1) {
        this.recordList = data.datas
      } else {
        this.recordList = this.recordList.concat(data.datas)
      }
      return data
    },

    async getMeetRecodsAction(page = 1, searchKey = '') {
      let param = {
        pageNumber: page,
        pageSize: 20,
        searchKey
      }
      const res = await getMeetRecodsAPI(param)
      this.meetRecords = res.datas
      // this.setStep(StepType.useMeetRecord)
      return res
    },

    onCheckedRecordChange(record) {
      this.checkedRecord = record;
    },

    async getCustomerRequireMentAction(meetInfo) {
      this.selectedRecord = meetInfo
      const res = await getCustomerRequireMentAPI(meetInfo.conferenceId)
      this.meetRequireMent = res
    },

    async sendCozeGoodPromptAction(query) {
      this.sendMessage(query)
      this.suggestions = []
      let tempChatList = []
      if (this.chatList) {
        tempChatList = this.chatList.map(({ ai, content_type, content }) => {
          return {
            role: ai ? 'assistant' : 'user',
            content_type: "text",
            content: content
          }
        })
      }
      const param = {
        user: this.userId || 'tempId',
        conversationId: this.currentChatId,
        query,
        chatHistory: tempChatList,
        isSafeWareProduct: this.isSafeWareProduct
      }
      let isFirst = true
      this.begainLoading()
      sendCozeGoodPromptAPI(param, (chunkObj, chatId) => {
        this.setStep(StepType.readStream)
        const { event } = chunkObj
        console.log('chunkObj: ' , chunkObj);
        if (event === CozeEventTypes.Message) {
          const { message } = chunkObj
          const { type, content, role, content_type } = message
          if (
            role === "assistant" &&
            type === "answer"
          ) {
            if (content.length === 0) return
            this.tempAnswer += content
            this.endLoading()
            this.receivedStreamMessage(this.tempAnswer, isFirst)
            isFirst = false
          }

          if (role === "assistant" &&
            type === "follow_up") {
            this.suggestions.push(message)
          }

          if (type === MessageTypes.verbose) {
            if (this.isValidJSON(content)) {
              const contentInfo = JSON.parse(content)
              this.isLoadingSuggestions = contentInfo.msg_type === 'generate_answer_finish'
            }
          }
        }

        if (event === CozeEventTypes.Done) {
          const msg = {
            message: this.tempAnswer,
            questions: this.suggestions.map((item) => item.content)
          }
          this.isLoadingSuggestions = false
          saveAiContentAPI(chatId, msg)
          this.tempAnswer = ''
          this.setStep(StepType.freeQA)
        }
      });
    },

    // 添加欢迎消息
    addWelcomeMessage() {
      this.addMessage(
        {
          content: "Hello，我是你的智能商品推荐伙伴，请选择你要售卖的商品类型。",
          messageDirection: messageDirectionType.received,
          isStart: true,
          products: this.categorys
        }
      );
    },

    sendMessage(text) {
      this.addMessage({
        content: text,
        messageDirection: "send",
        ai: false
      });
    },

    receivedMessage(text, messageType = '') {
      this.addMessage({
        content: text,
        messageDirection: messageDirectionType.received,
        messageType,
        ai: true
      });
      console.log('chatList :>> ', this.chatList);
    },

    receivedStreamMessage(v, isFirst) {
      if (isFirst) {
        this.receivedMessage(v, 'answer')
      } else {
        for (let i = this.chatList.length - 1; i > 0; i--) {
          let chatInfo = this.chatList[i];
          if (chatInfo.messageType === 'answer') {
            chatInfo.content = v
            break;
          }
        }
      }
    },

    addMessage(msg = { isStart: false, isResult: false }) {
      console.log(msg);
      this.chatList.push(msg)
    },

    setStep(step) {
      this.currentStepType = step
    },

    begainLoading() {
      this.isLoading = true
      this.addMessage({
        content: '正在思考',
        isLoading: true
      })
    },

    endLoading() {
      this.isLoading = false
      this.chatList = this.chatList.filter((item) => {
        return !item.isLoading
      })
    },

    changeEditDialogState(v, editChatId) {
      const targetItem = this.recordList.filter((item) => {
        return item.id === editChatId
      })[0]
      const name = targetItem ? targetItem.topic : ''
      this.changeDialogFieldValue(name)
      this.showEditDialog = v
      if (editChatId) {
        this.editChatId = editChatId
      }
    },

    changeDialogFieldValue(v) {
      this.dialogFieldValue = v
    },

    // 开始批量编辑
    begainBatchEdit() {
      this.isBatchEdit = true
    },

    // 结束批量编辑
    endBatchEdit() {
      this.isBatchEdit = false
      this.onCheckedRecord = []
    },

    changeCheckedRecord(checked, id) {
      if (checked) {
        this.onCheckedRecord.push(id)
      } else {
        this.onCheckedRecord = this.onCheckedRecord.filter((item) => item !== id)
      }
    },

    changeAllRecordChecked(checked) {
      console.log('changeAllRecordChecked :>> ', checked);
      if (checked) {
        this.onCheckedRecord = this.recordList.map((v) => v.id)
      } else {
        this.onCheckedRecord = []
      }
    },

    clearSelectedRecord() {
      this.selectedRecord = null
      this.checkedRecord = null
    },

    stopAnswer() {
      this.cancelRequest()
      this.receivedMessage('已停止回答')
      if (this.messageType === MessageTypes.recommend) {
        this.showExtra = true
      }
    },

    cancelRequest() {
      this.endLoading()
      cancelFetchRequest()
    }
  }
});
